# hook-exclude-modules.py
import logging
import importlib.metadata
from PyInstaller.utils.hooks import logger, collect_all

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def get_excludes():
    # 获取所有已安装的包
    installed_packages = [dist.metadata['Name'] for dist in importlib.metadata.distributions()]

    # 定义需要保留的包
    needed_packages = ['cffi', 'cryptography', 'pycparser', 'pycryptodome']

    # 生成排除列表
    excludes = [pkg for pkg in installed_packages if pkg not in needed_packages]

    # 打印排除列表
    logger.info(f'排除的包：{excludes}')
    return excludes


def hook(hook_api):
    # 收集所有需要的模块和数据文件
    datas, binaries, hiddenimports = collect_all('code', include_py_files=False)

    # 添加需要的隐藏导入
    hiddenimports += []

    # 动态生成排除列表
    excludedimports = get_excludes()

    # 设置排除列表
    hook_api.excludes.extend(excludedimports)

    # 记录排除的模块
    logger.info("Excluding modules: %s", ', '.join(excludedimports))

    # 返回收集到的数据
    return datas, binaries, hiddenimports

#
get_excludes()
